from lib2to3.pytree import convert
from markdown import Markdown, markdown
from myblogs.models.fields import CustomDateTimeField
import django.utils.timezone as timezone
from django.db import models

class Tag(models.Model):
    tag = models.CharField(max_length=10,verbose_name="标签")
    def __str__(self):
        return self.tag

class Catagory(models.Model):
    catagory = models.CharField(max_length=10,verbose_name="目录")
    def __str__(self):
        return self.catagory
    
class Article(models.Model):
    avatar = models.ImageField(upload_to="uploads/avatar")
    author = models.CharField(max_length=32,verbose_name="作者",null=True)
    title = models.CharField(max_length=32,verbose_name='文章标题')
    content = models.TextField(verbose_name='文章内容')
    tags = models.ManyToManyField(Tag,related_name="title")
    catagory = models.ForeignKey('Catagory',on_delete=models.CASCADE,related_name="title")
    created_time = CustomDateTimeField(default=timezone.now,verbose_name="创建日期")
    
    #新增方法，将body转换为带html标签的正文
    def get_md(self):
        md = Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ]
        )
        md_content = md.convert(self.content)
        #toc是渲染后的目录
        return md_content,md.toc
    
    class Meta:
        ordering = ['-created_time']
    
    def __str__(self):
        return self.title